package cn.aitrox.ry.util;

import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class JacksonUtil {
    private static ObjectMapper objectMapper = new ObjectMapper();

    public JacksonUtil() {
    }

    public static <T> T Json2Obj(String json, TypeReference<T> tr) throws JsonParseException, JsonMappingException, IOException {
        T obj = null;
        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.setSerializationInclusion(Include.NON_NULL);
        obj = mapper.readValue(json, tr);
        return obj;
    }

    public static Map<String, Object> Json2Map(String json) throws JsonParseException, JsonMappingException, IOException {
        Map<String, Object> result = null;
        ObjectMapper mapper = new ObjectMapper();
        result = (Map)mapper.readValue(json, Map.class);
        return result;
    }

    public static String Obj2Json(Object obj) throws JsonProcessingException {
        return objectMapper.writeValueAsString(obj);
    }

    public static String keyVal2Json(Object... objs) throws JsonProcessingException {
        if (objs.length % 2 != 0) {
            return "";
        } else {
            ObjectMapper objectMapper = new ObjectMapper();
            Map map = new HashMap();

            for(int i = 0; i < objs.length; i += 2) {
                map.put(objs[i], objs[i + 1]);
            }

            String json = objectMapper.writeValueAsString(map);
            return json;
        }
    }

    public static String array2Json(String... params) throws JsonProcessingException {
        if (params.length % 2 == 0) {
            Map<String, Object> map = new HashMap(params.length / 2);

            for(int i = 0; i < params.length; ++i) {
                if (i % 2 == 0) {
                    map.put(params[i], params[i + 1]);
                }
            }

            return Obj2Json(map);
        } else {
            return null;
        }
    }
}